package com.example.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.common.CustomException;
import com.example.entity.Category;
import com.example.entity.Dish;
import com.example.entity.Setmeal;
import com.example.mapper.CategoryMapper;
import com.example.service.ICategoryService;
import com.example.service.IDishService;
import com.example.service.ISetmealService;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 * 菜品及套餐分类 服务实现类
 * </p>
 *
 * @author czx
 * @since 2022-04-28
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements ICategoryService {

    @Resource
    @Lazy
    private IDishService dishService;

    @Resource
    private ISetmealService setmealService;

    /**
     * 分页查询
     *
     * @param page     分页页数
     * @param pageSize 分页大小
     * @return 当前页信息
     */
    @Override
    public Page<Category> page(int page, int pageSize) {
        //构造分页构造器
        Page<Category> pageInfo = new Page<>(page, pageSize);
        //构造条件构造器
        LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<>();
        //添加排序条件
        wrapper.orderByDesc(Category::getCreateTime);
        // 执行查询
        return baseMapper.selectPage(pageInfo, wrapper);
    }

    /**
     * 根据id删除分类信息,删除前需要判断
     *
     * @param id 分类id
     * @return 删除结果
     */
    @Override
    public void remove(Long id) {
        LambdaQueryWrapper<Dish> dishLambdaQueryWrapper = new LambdaQueryWrapper<>();
        dishLambdaQueryWrapper.eq(Dish::getCategoryId, id);
        long count = dishService.count(dishLambdaQueryWrapper);
        //是否关联菜品
        if (count > 0L) {
            //抛出一个业务异常
            throw new CustomException("当前分类下关联了菜品，不能删除");
        }
        LambdaQueryWrapper<Setmeal> setmealLambdaQueryWrapper = new LambdaQueryWrapper<>();
        setmealLambdaQueryWrapper.eq(Setmeal::getCategoryId, id);
        long count1 = setmealService.count(setmealLambdaQueryWrapper);
        //是否关联套餐
        if (count1 > 0L) {
            //抛出一个业务异常
            throw new CustomException("当前分类下关联了套餐，不能删除");
        }
        //正常删除分类
        baseMapper.deleteById(id);
    }

    /**
     * 查询分类列表
     *
     * @param category 分类的条件
     * @return 分类列表信息
     */
    @Override
    public List<Category> list(Category category) {
        //创建条件构造器
        LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<>();
        //添加查询条件
        wrapper.eq(category.getType() != null, Category::getType, category.getType());
        //添加排序条件
        wrapper.orderByAsc(Category::getSort).orderByAsc(Category::getCreateTime);
        //返回查询结果
        return baseMapper.selectList(wrapper);
    }


}
